package com.yuanqi.service;

import com.yuanqi.domain.Receipt;
import com.yuanqi.repository.ReceiptRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class ReceiptService {
    
    @Autowired
    private ReceiptRepository receiptRepository;
    
    public List<Receipt> getAllReceipts() {
        return receiptRepository.findAll();
    }
    
    public Optional<Receipt> getReceiptById(Long id) {
        return receiptRepository.findById(id);
    }
    
    public List<Receipt> getReceiptsByCustomer(Long customerId) {
        return receiptRepository.findByCustomerId(customerId);
    }
    
    public List<Receipt> getReceiptsByDateRange(LocalDate startDate, LocalDate endDate) {
        return receiptRepository.findByReceiptDateBetween(startDate, endDate);
    }
    
    public Receipt createReceipt(Receipt receipt) {
        if (receiptRepository.existsByReceiptCode(receipt.getReceiptCode())) {
            throw new RuntimeException("收款单号已存在");
        }
        receipt.setCreatedAt(LocalDateTime.now());
        return receiptRepository.save(receipt);
    }
    
    public Receipt updateReceipt(Long id, Receipt receiptDetails) {
        Receipt receipt = receiptRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("收款记录不存在"));
        
        receipt.setCustomerId(receiptDetails.getCustomerId());
        receipt.setReceiptDate(receiptDetails.getReceiptDate());
        receipt.setAmount(receiptDetails.getAmount());
        receipt.setMethod(receiptDetails.getMethod());
        receipt.setCurrency(receiptDetails.getCurrency());
        receipt.setRemark(receiptDetails.getRemark());
        
        return receiptRepository.save(receipt);
    }
    
    public void deleteReceipt(Long id) {
        receiptRepository.deleteById(id);
    }
    
    public Double getTotalReceiptAmount(LocalDate startDate, LocalDate endDate) {
        return receiptRepository.getTotalReceiptAmount(startDate, endDate);
    }
}


